<template>
  <div
    class="preview-module"
    style="white-space: pre-wrap;"
    v-html="html"
    @click="getpreview($event)"
  ></div>
</template>

<script>
import { ImagePreview } from "vant";
export default {
  components: {},
  props: {
    html: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      // 图片列表
      imgList: []
    };
  },
  watch: {
    html(newV, oldV) {
      if (!newV) return;
      this.getImgSrc();
    }
  },
  mounted() {
    this.getImgSrc();
  },
  methods: {
    // 获取所有富文本图片
    getImgSrc() {
      // 非空判断
      if (!this.html) return;
      var imgList = [];
      this.html.replace(
        /<img [^>]*src=['"]([^'"]+)[^>]*>/g,
        (match, capture) => {
          imgList.push(capture);
        }
      );
      this.imgList = imgList;
    },
    // 点击
    getpreview(e) {
      if (e.target.tagName == "IMG" && e.target.src) {
        // 当前图片
        const currentSrc = e.target.src;
        // 当前下标
        let currentIndex = 0;
        for (let i = 0; i < this.imgList.length; i++) {
          if (this.imgList[i] === currentSrc) {
            currentIndex = i;
            break;
          }
        }
        ImagePreview({
          images: this.imgList,
          startPosition: currentIndex,
          closeOnPopstate: true,
          closeable: true
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.preview-module {
  overflow: hidden;
  padding: 20px 0;
  word-wrap: break-word;
  word-break: break-all;
  ::v-deep img {
    display: block;
    max-width: 100%;
    height: 100%;
    margin: 0 auto;
  }
  ::v-deep video {
    width: 100%;
    height: 520px;
  }
  ::v-deep pre {
    word-wrap: break-word;
    word-break: break-all;
    white-space: pre-wrap;
  }
  ::v-deep p {
    margin: 0;
    padding: 0;
  }
}
</style>
